<?php

namespace App\Http\Controllers\Import;

use App\Http\Controllers\Admin\CommonController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\QrCodeController;
use App\Models\AnswerActivity;
use App\Models\AnswerActivityArea;
use App\Models\AnswerActivityUnit;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;


/**
 * excel导入功能
 */
class AnswerActivityUnitImport extends Controller
{
    public $model = null;
    public $request = null;
    public $commonObj = null;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->model = new AnswerActivityUnit();
        $this->commonObj = new CommonController();
    }

    /**
     * 活动单位导入
     * @param file  excel 文件名
     * @param act_id  活动id
     * @param is_update  遇到重复数据，是否覆盖更新  1 更新  2 不更新 （默认2）
     */
    public function index()
    {
        set_time_limit(500);
        ini_set('memory_limit', '1024M');

        $is_update = $this->request->input('is_update', 2);
        $act_id = $this->request->input('act_id', '');

        //判断是否是单位联盟活动
        $isAllowAddUnit = $this->model->isAllowAddUnit($act_id);
        if ($isAllowAddUnit !== true) {
            return $this->returnApi(202, $isAllowAddUnit);
        }
        $activityModel = new AnswerActivity();
        $node = $activityModel->where('id', $act_id)->where('is_del', 1)->value('node');
        if ($node == 1) {
            return $this->commonObj->returnApi(202, '此活动不支持导入单位');
        }

        DB::beginTransaction();
        try {

            //图片保存目录
            $img_dir = public_path('uploads') . '/img/' . date('Y-m-d') . '/';
            if (!is_dir($img_dir)) {
                @mkdir($img_dir, 0777, true);
            }
            $importObj = new Import();
            $data = $importObj->getData($this->request, 'file', 'activity_unit_import', $img_dir);

            // $data = $this->getData('file', 'activity_unit_import');


            $checkTemplate = $this->checkTemplate($data, $node);
            if ($checkTemplate !== true) {
                return $this->commonObj->returnApi(202, '模板有误，请重新下载模板');
            }

            array_shift($data); //去掉第一个元素，数据中没删除头部    // $data = $this->getData('file', 'activity_unit_import'); 使用这行就是删除了第一行的


            // $success = 0;//成功个数
            $error = 0; //失败个数
            $error_msg = ''; //失败原因
            $activityAreaModel = new AnswerActivityArea();
            foreach ($data as $key => $val) {
                $serial = $val[0];
                $name = $val[1];
                if ($node == 2) {
                    $nature_name = $val[2];
                    $intro = $val[3];
                    $words = $val[4];

                    $img = $val[5];

                    $province = $val[6];
                    $city = $val[7];
                    $district = $val[8];
                    $address = $val[9];
                } else {
                    $area_name = $val[2];
                    $nature_name = $val[3];
                    $intro = $val[4];
                    $words = $val[5];
                    //判断区域在系统是否存在
                    $area_id = $activityAreaModel->where('name', $area_name)->where('act_id', $act_id)->where('is_del', 1)->value('id');
                    if (empty($area_id)) {
                        $error++;
                        $error_msg .= '[ID：“' . $serial . '”区域名称在系统不存在]';
                        continue;
                    }

                    $img = $val[6];

                    $province = $val[7];
                    $city = $val[8];
                    $district = $val[9];
                    $address = $val[10];
                }
                $img = substr($img, 0, 1) == '/' ? substr($img, 1, strlen($img)) : $img; //去掉第一个 / 斜线

                /*生成经纬度*/
                $lon = '';
                $lat = '';
                if (!empty($province) && !empty($city) && !empty($district) && !empty($address)) {
                    $map = $this->getLonLatByAddress($province . $city . $district . $address);
                    if (is_string($map)) {
                        $error++;
                        $error_msg .= '[序号：“' . $serial . '”' . $map . ']';
                        continue;
                    }

                    $lon = $map['lon'];
                    $lat = $map['lat'];
                } else {
                    $error++;
                    $error_msg .= '[序号：“' . $serial . '”地址信息有误，请重新输入]';
                    continue;
                }

                $nature = $this->model->getNatureIdByName($nature_name);
                if (empty($nature)) {
                    $error++;
                    $error_msg .= '[序号：“' . $serial . '”单位性质输入错误]';
                    continue;
                }
                if (empty($name)) {
                    $error++;
                    $error_msg .= '[序号：“' . $serial . '”单位名称不能为空]';
                    continue;
                }

                $limitWords = $this->model->limitWords($words);
                if ($limitWords !== true) {
                    $error++;
                    $error_msg .= '[序号：“' . $serial . '”' . $limitWords . ']';
                    continue;
                }

                $letter = get_first_charter($name);

                //判断名称是否存在
                $condition[] = ['act_id', '=', $act_id];
                $is_exists = $this->model->nameIsExists($name, 'name', null, 1, $condition);
                if (empty($is_exists)) {
                    $activityUnitModel = new AnswerActivityUnit();
                    $activityUnitModel->add([
                        'act_id' => $act_id,
                        'area_id' => $area_id ?? 0,
                        'name' => $name,
                        'img' => $img,
                        'nature' => $nature,
                        'intro' => $intro,
                        'words' => $words,
                        'letter' => $letter,
                        'lon' => $lon,
                        'lat' => $lat,
                        'province' => $province,
                        'city' => $city,
                        'district' => $district,
                        'address' => $address,
                    ]); //覆盖更新数据

                    //生成二维码
                    $qrCodeObj = new QrCodeController();
                    $qr_code = $qrCodeObj->getQrCode('answer_activity_unit');
                    if ($qr_code === false) {
                        Log::error("二维码生成失败,请手动生成");
                        continue;
                    }
                    $qr_data = $this->getDomainName() . '/' . config('other.project_name') . 'wx/pagesGames/activityLoading/index?from=readshare_activity&token=' . $qr_code; //渝中区二维码的链接  扫码跳转渝中区二维码
                    $qr_url = $qrCodeObj->setQr($qr_data, true, 360, 1);
                    $activityUnitModel->where('id', $activityUnitModel->id)->update(['qr_code' => $qr_code, 'qr_url' => $qr_url]);
                } else {
                    if ($is_update == 1) {
                        $this->model->change([
                            'id' => $is_exists->id,
                            'area_id' => $area_id ?? 0,
                            'name' => $name,
                            'img' => $img,
                            'nature' => $nature,
                            'intro' => $intro,
                            'words' => $words,
                            'letter' => $letter,
                            'lon' => $lon,
                            'lat' => $lat,
                            'province' => $province,
                            'city' => $city,
                            'district' => $district,
                            'address' => $address,
                        ]); //覆盖更新数据

                        //删除掉之前的图片
                        if ($img && $is_exists->img) {
                            $this->commonObj->deleteFile($is_exists->img);
                        }
                    } else {
                        $error++;
                        $error_msg .= '[ID：“' . $serial . '” 单位名称:' . $name . ' 已存在,不允许重复添加]';
                        continue;
                    }
                }
            }

            DB::commit();
            $return_msg = "导入成功，" . '错误: ' . $error . ' 个';
            if ($error) $return_msg .= '错误原因:' . $error_msg;

            return $this->commonObj->returnApi(200, $return_msg, true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->commonObj->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 检查模板是否正确 (必须与模板对应)
     *
     * @param [type] $type
     * @return void
     */
    public function checkTemplate($data, $node)
    {
        if ($node == 3) {
            if (
                $data[0][0] != '序号' ||
                $data[0][1] != '单位名称' ||
                $data[0][2] != '所属区域' ||
                $data[0][3] != '单位性质' ||
                $data[0][4] != '单位简介' ||
                $data[0][5] != '单位赠言' ||
                $data[0][6] != '图片'     ||
                $data[0][7] != '省' ||
                $data[0][8] != '市' ||
                $data[0][9] != '区/县' ||
                $data[0][10] != '详细地址'
            ) {
                return false;
            }
        } else {
            if (
                $data[0][0] != '序号' ||
                $data[0][1] != '单位名称' ||
                $data[0][2] != '单位性质' ||
                $data[0][3] != '单位简介' ||
                $data[0][4] != '单位赠言' ||
                $data[0][5] != '图片' ||
                $data[0][6] != '省' ||
                $data[0][7] != '市' ||
                $data[0][8] != '区/县' ||
                $data[0][9] != '详细地址'

            ) {
                return false;
            }
        }
        return true;
    }


    /**
     * 处理数据
     * @param $file_name  上传文件名
     * @param $file_dir  存放文件夹
     */
    public function getData($file_name = 'file', $file_dir = 'file')
    {
        if ($this->request->file($file_name) == null) throw new Exception('请添加Excel表格......'); // return $this->returnApi(202, '请添加Excel表格......');

        //接收前台文件
        if (empty($_FILES[$file_name]['name'])) throw new Exception('上传文件不能为空'); //return $this->returnApi(202, "上传文件不能为空");
        if (empty($_FILES[$file_name]['size']) || $_FILES[$file_name]['size'] > 5242880) throw new Exception('上传文件不能大于5M'); //return $this->returnApi(202, "上传文件不能大于5M");

        //判断文件名
        $name = explode('.', $_FILES[$file_name]['name'])[1];
        if ($name !== 'xls' && $name !== 'xlsx') throw new Exception('上传文件后缀名不允许，只能上传 .xls 或 .xlsx 的文件'); //return $this->returnApi(202, "上传文件后缀名不允许，只能上传 .xls 或 .xlsx 的文件");

        // 这个方法是 自定义文件名 文件上传方法 。 将获取到的Excel文件 保存到/public/upload/book_import/ 文件中。
        $foldername =  $file_dir . '/' . date('Y-m-d'); //$file_name.'/'.date('Y-m-d')  存放路径，按日志存储
        $file = $this->request->file($file_name)->store($foldername);

        if ($file) {
            //$this->request->file($file_name)->getRealPath(); 获取临时文件地址
            $file_addr = public_path('uploads') . '/' . $file; //完整地址
            /*  Excel::load($file_addr, function ($reader) {return $reader->all();}); */
            $delTitle = 1; //指定头行数  删除它
            $excel = new Import($delTitle);
            Excel::import($excel, $file_addr);
            if ($excel->data) {
                return $excel->data->toArray(); //获取所有的数据（数组）
            }
            throw new Exception('导入失败');
        }
        throw new Exception('请添加Excel表格......'); //return $this->returnApi(202, "导入失败");
    }
}
